package com.guoproject.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;

import com.guoproject.BaseActivity;
import com.guoproject.R;
import com.guoproject.utils.CommonTools;
import com.guoproject.widget.HomeSearchBarPopupWindow;
import com.guoproject.widget.HomeSearchBarPopupWindow.onSearchBarItemClickListener;
import com.guoproject.widgets.jazzviewpager.JazzyViewPager;
import com.guoproject.widgets.jazzviewpager.JazzyViewPager.TransitionEffect;
import com.guoproject.widgets.jazzviewpager.OutlineContainer;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class MainActivity extends BaseActivity implements OnClickListener, onSearchBarItemClickListener {
	private static final String TAG = "MainActivity";
	// ============== 顶部 ===================
	private ImageButton mCamerButton = null;
	private LinearLayout mTopLayout = null;
	private HomeSearchBarPopupWindow mBarPopupWindow = null;
	// ============== 中部 ===================
	// ============== 底部 ===================
	private ImageView im_bottom_plus;
	private FrameLayout fl_bottom_discount;
	private FrameLayout fl_bottom_concern;
	private FrameLayout fl_bottom_nutrition;
	private FrameLayout fl_bottom_more;
	private FrameLayout fl_tab_toolbar_plus;
	private int times = 2;
	// ============== 广告切换 ===================
	private String mImageUrl = null;
	private List<String> mImageUrls = new ArrayList<String>();
	private JazzyViewPager mViewPager = null;
	private LinearLayout mIndicator = null;
	/**
	 * 装ViewPager中ImageView的数组
	 */
	private ImageView[] mImageViews;
	ImageLoader imageLoader;
	private static final int MSG_CHANGE_PHOTO = 1;
	/**
	 * 装指引的ImageView数组
	 */
	private ImageView[] mIndicators;
	/** 图片自动切换时间 */
	private static final int PHOTO_CHANGE_TIME = 3000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 取消标题栏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration
				.createDefault(MainActivity.this));
		mHandler = new Handler(getMainLooper()) {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {
				case MSG_CHANGE_PHOTO:
					int index = mViewPager.getCurrentItem();
					if (index == mImageUrls.size() - 1) {
						index = -1;
					}
					mViewPager.setCurrentItem(index + 1);
					mHandler.sendEmptyMessageDelayed(MSG_CHANGE_PHOTO,
							PHOTO_CHANGE_TIME);
				}
			}

		};
		findViewById();
		initData();
		initView();
		mCamerButton.setOnClickListener(this);
		mBarPopupWindow = new HomeSearchBarPopupWindow(this,
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		mBarPopupWindow.setOnSearchBarItemClickListener(this);
	}

	private void initData() {
		mImageUrl = "drawable://" + R.drawable.p1;
		mImageUrls.add(mImageUrl);

		mImageUrl = "drawable://" + R.drawable.p2;
		mImageUrls.add(mImageUrl);

		mImageUrl = "drawable://" + R.drawable.p3;
		mImageUrls.add(mImageUrl);

		mImageUrl = "drawable://" + R.drawable.p4;
		mImageUrls.add(mImageUrl);

		mImageUrl = "drawable://" + R.drawable.p5;
		mImageUrls.add(mImageUrl);

		mImageUrl = "drawable://" + R.drawable.p6;
		mImageUrls.add(mImageUrl);

		mImageUrl = "drawable://" + R.drawable.p7;
		mImageUrls.add(mImageUrl);

		mImageUrl = "drawable://" + R.drawable.p8;
		mImageUrls.add(mImageUrl);
		for (String url : mImageUrls) {
			System.out.println(url);
		}
	}

	@Override
	protected void initView() {
		// ======= 初始化ViewPager ========
		mIndicators = new ImageView[mImageUrls.size()];
		Log.i(TAG, "mIndicators大小： " + mIndicators.length);
		if (mImageUrls.size() <= 1) {
			// 当首页广告展示的内容只有一页的话下面的指示条也就没有必要存在了
			mIndicator.setVisibility(View.GONE);
		}

		for (int i = 0; i < mIndicators.length; i++) {
			ImageView imageView = new ImageView(this);
			LayoutParams params = new LayoutParams(0,
					LayoutParams.WRAP_CONTENT, 1.0f);
			if (i != 0) {
				params.leftMargin = 1;
			}
			imageView.setLayoutParams(params);
			mIndicators[i] = imageView;
			if (i == 0) {
				mIndicators[i]
						.setBackgroundResource(R.drawable.android_activities_cur);
			} else {
				mIndicators[i]
						.setBackgroundResource(R.drawable.android_activities_bg);
			}

			mIndicator.addView(imageView);
		}
		mImageViews = new ImageView[mImageUrls.size()];

		for (int i = 0; i < mImageViews.length; i++) {
			ImageView imageView = new ImageView(this);
			imageView.setScaleType(ScaleType.CENTER_CROP);
			mImageViews[i] = imageView;
		}

		mViewPager.setTransitionEffect(TransitionEffect.Accordion);
		mViewPager.setCurrentItem(0);
		mHandler.sendEmptyMessageDelayed(MSG_CHANGE_PHOTO, PHOTO_CHANGE_TIME);

		mViewPager.setAdapter(new MyAdapter());
		mViewPager.setOnPageChangeListener(new MyPageChangeListener());
		mViewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (mImageUrls.size() == 0 || mImageUrls.size() == 1)
					return true;
				else
					return false;
			}
		});

	}

	@Override
	protected void findViewById() {
		// 顶部
		mCamerButton = (ImageButton) findViewById(R.id.index_camer_button);
		im_bottom_plus = (ImageView) findViewById(R.id.im_bottom_plus);
		im_bottom_plus.setBackgroundResource(R.drawable.tab_toolbar_plus);
		mTopLayout = (LinearLayout) findViewById(R.id.index_top_layout);
		// 中间
		// 底部
		fl_bottom_discount = (FrameLayout) findViewById(R.id.fl_bottom_discount);
		fl_bottom_concern = (FrameLayout) findViewById(R.id.fl_bottom_concern);
		fl_bottom_nutrition = (FrameLayout) findViewById(R.id.fl_bottom_nutrition);
		fl_bottom_more = (FrameLayout) findViewById(R.id.fl_bottom_more);
		fl_tab_toolbar_plus = (FrameLayout) findViewById(R.id.fl_tab_toolbar_plus);
		fl_bottom_more.setOnClickListener(this);
		fl_bottom_nutrition.setOnClickListener(this);
		fl_bottom_concern.setOnClickListener(this);
		fl_bottom_discount.setOnClickListener(this);
		fl_tab_toolbar_plus.setOnClickListener(this);

		// ============== 广告切换 ===================
		mViewPager = (JazzyViewPager) findViewById(R.id.index_product_images_container);
		mIndicator = (LinearLayout) findViewById(R.id.index_product_images_indicator);

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.index_camer_button:
			int height = mTopLayout.getHeight()
					+ CommonTools.getStatusBarHeight(this);
			mBarPopupWindow.showAtLocation(mTopLayout, Gravity.TOP, 0, height);
			break;
		case R.id.fl_bottom_discount:
			Log.i(TAG, "fl_bottom_discount");
			Intent discountIntent = new Intent(MainActivity.this,DiscountActivity.class);
			startActivity(discountIntent);
			break;
		case R.id.fl_bottom_concern:
			Intent concernIntent = new Intent(this, ConcernActivity.class);
			startActivity(concernIntent);
			Log.i(TAG, "fl_bottom_concern");
			break;
		case R.id.fl_bottom_nutrition:
			Intent nutritionIntent = new Intent(this, NutritionActivity.class);
			startActivity(nutritionIntent);
			Log.i(TAG, "fl_bottom_nutrition");
			break;
		case R.id.fl_bottom_more:
			Intent moreIntent = new Intent(this, MoreActivity.class);
			startActivity(moreIntent);
			Log.i(TAG, "fl_bottom_more");
			break;
		case R.id.fl_tab_toolbar_plus:
			Log.i(TAG, "fl_tab_toolbar_plus");
			if (times % 2 == 1) {
				im_bottom_plus
						.setBackgroundResource(R.drawable.tab_toolbar_plus);
				times += 1;

			} else if (times % 2 == 0) {
				im_bottom_plus
						.setBackgroundResource(R.drawable.tab_toolbar_plusback);
				times += 1;

			}
			break;
		}

	}

	public class MyAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return mImageViews.length;
		}

		@Override
		public boolean isViewFromObject(View view, Object obj) {
			if (view instanceof OutlineContainer) {
				return ((OutlineContainer) view).getChildAt(0) == obj;
			} else {
				return view == obj;
			}
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView(mViewPager
					.findViewFromObject(position));
		}

		@Override
		public Object instantiateItem(View container, int position) {
			imageLoader.displayImage(mImageUrls.get(position),
					mImageViews[position]);
			((ViewPager) container).addView(mImageViews[position], 0);
			mViewPager.setObjectForPosition(mImageViews[position], position);
			return mImageViews[position];
		}
	}

	/**
	 * 当ViewPager中页面的状态发生改变时调用
	 * 
	 * @author Administrator
	 * 
	 */
	private class MyPageChangeListener implements OnPageChangeListener {

		/**
		 * This method will be invoked when a new page becomes selected.
		 * position: Position index of the new selected page.
		 */
		public void onPageSelected(int position) {
			setImageBackground(position);
		}

		public void onPageScrollStateChanged(int arg0) {

		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	/**
	 * 设置选中的tip的背景
	 * 
	 * @param selectItemsIndex
	 */
	private void setImageBackground(int selectItemsIndex) {
		for (int i = 0; i < mIndicators.length; i++) {
			if (i == selectItemsIndex) {
				mIndicators[i]
						.setBackgroundResource(R.drawable.android_activities_cur);
			} else {
				mIndicators[i]
						.setBackgroundResource(R.drawable.android_activities_bg);
			}
		}
	}

	@Override
	public void onBarCodeButtonClick() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onCameraButtonClick() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onColorButtonClick() {
		// TODO Auto-generated method stub
		
	}

}
